//
//  CameraView.swift
//  replaykit
//
//  Created by zhang on 2025/7/31.
//

import SwiftUI
import AVFoundation

struct CameraView: UIViewRepresentable {
    let cameraManager: CameraManager
    
    func makeUIView(context: Context) -> UIView {
        print("CameraView: 创建UIView")
        let view = UIView()
        view.backgroundColor = .black
        
        // 创建预览层并立即设置
        let previewLayer = AVCaptureVideoPreviewLayer(session: cameraManager.session)
        previewLayer.videoGravity = .resizeAspectFill
        previewLayer.frame = view.bounds
        
        // 将预览层添加到视图
        view.layer.addSublayer(previewLayer)
        
        // 保存预览层引用到cameraManager
        cameraManager.previewLayer = previewLayer
        
        print("CameraView: 预览层已创建并添加到视图")
        print("CameraView: 预览层frame: \(previewLayer.frame)")
        print("CameraView: 相机会话运行状态: \(cameraManager.session.isRunning)")
        print("CameraView: 预览层videoGravity: \(previewLayer.videoGravity.rawValue)")
        print("CameraView: 视图层级数量: \(view.layer.sublayers?.count ?? 0)")
        
        // 强制刷新预览层
        DispatchQueue.main.async {
            previewLayer.setNeedsDisplay()
            print("CameraView: 已调用setNeedsDisplay")
        }
        
        return view
    }
    
    func updateUIView(_ uiView: UIView, context: Context) {
        print("CameraView: 更新UIView，相机准备状态: \(cameraManager.isCameraReady)")
        
        // 更新预览层frame以适配视图大小
        if let previewLayer = cameraManager.previewLayer {
            previewLayer.frame = uiView.bounds
            print("CameraView: 更新预览层frame: \(uiView.bounds)")
            
            // 强制刷新预览层
            previewLayer.setNeedsDisplay()
        }
    }
} 